package top.go2do.auth.business.permission.service;

import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.go2do.common.dao.ApplicationRepository;
import top.go2do.auth.business.app.enumeration.PermType;
import top.go2do.common.module.ApplicationPO;
import top.go2do.auth.business.permission.dao.PermissionRepository;
import top.go2do.auth.business.permission.module.*;
import top.go2do.common.dao.UserRepository;
import top.go2do.common.module.UserPO;
import top.go2do.auth.exception.AuthErrorCode;
import top.go2do.auth.exception.AuthException;
import top.go2do.common.module.pageQuery.PageResult;
import top.go2do.common.utils.IdUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/6/12 11:37
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private IdUtils idUtils;

    @Autowired
    private ApplicationRepository applicationRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public PermissionPO create(PermissionCreateForm createForm) {
        String appId = createForm.getAppId();
        String permCode = createForm.getPermCode();
        String permName = createForm.getPermName();
        PermissionPO permissionPO = permissionRepository.findByAppIdAndPermCode(appId, permCode);
        if (permissionPO != null) {
            throw new AuthException(AuthErrorCode.PERM_CODE_EXIST);
        }
        permissionPO = permissionRepository.findByAppIdAndPermName(appId, permName);
        if (permissionPO != null) {
            throw new AuthException(AuthErrorCode.PERM_NAME_EXIST);
        }
        permissionPO = new PermissionPO();
        BeanUtils.copyProperties(createForm, permissionPO);
        Long permId = idUtils.getSnowflakeId();
        Long userId = createForm.getUserId();

        permissionPO.setPermId(permId);
        permissionPO.setCreatedBy(userId);
        permissionPO.setUpdatedBy(userId);
        permissionRepository.save(permissionPO);
        return this.getById(permId);
    }

    @Override
    public void modifyById(PermissionModifyForm modifyForm) {
        Long permId = modifyForm.getPermId();
        PermissionPO permissionPO = this.getById(permId);
        String permName = modifyForm.getPermName();
        String permCode = modifyForm.getPermCode();
        Integer permType = modifyForm.getPermType();
        String appId = permissionPO.getAppId();
        if (StringUtils.hasText(permName)) {
            PermissionPO target = permissionRepository.findByAppIdAndPermName(appId, permName);
            if (target != null && !target.getPermId().equals(permId)) {
                throw new AuthException(AuthErrorCode.PERM_NAME_EXIST);
            }
            permissionPO.setPermName(permName);
        }
        if (StringUtils.hasText(permCode)) {
            PermissionPO target = permissionRepository.findByAppIdAndPermCode(appId, permCode);
            if (target != null && !target.getPermId().equals(permId)) {
                throw new AuthException(AuthErrorCode.PERM_CODE_EXIST);
            }
            permissionPO.setPermCode(permCode);
        }
        if (permType != null) {
            permissionPO.setPermType(permType);
        }
        permissionPO.setUpdatedBy(modifyForm.getUserId());
        permissionRepository.save(permissionPO);
    }

    @Override
    public void removeById(Long id) {
        this.getById(id);
        permissionRepository.deleteById(id);
    }

    @Override
    public PermissionPO getById(Long id) {
        PermissionPO permissionPO = permissionRepository.findById(id).orElse(null);
        if (permissionPO == null) {
            throw new AuthException(AuthErrorCode.PERM_ID_NOT_EXIST);
        }
        return permissionPO;
    }

    @Override
    public PageResult<PermissionPO> pageQuery(PermissionQueryCondition condition) {
        Sort.Direction direction = Sort.Direction.fromString(condition.getDirection());
        Sort sort = Sort.by(direction, condition.getOrderBy());

        /**
         * pageNumber 从0开始
         */
        Integer page = condition.getPage() - 1;
        Integer size = condition.getSize();
        Pageable pageable = PageRequest.of(page, size, sort);
        Specification<PermissionPO> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (condition.getAppId() != null) {
                predicates.add(cb.equal(root.get("appId"), condition.getAppId() ));
            }

            if (condition.getPermType() != null) {
                predicates.add(cb.equal(root.get("permType"), condition.getPermType() ));
            }

            if (condition.getPermName() != null) {
                predicates.add(cb.like(root.get("permName"), "%" + condition.getPermName() + "%"));
            }

            if (condition.getPermCode() != null) {
                predicates.add(cb.like(root.get("permCode"), "%" + condition.getPermCode() + "%"));
            }

            if (condition.getKeyword() != null) {
                Predicate appIdMatch = cb.like(root.get("permName"), "%" + condition.getKeyword() + "%");
                Predicate appNameMatch = cb.like(root.get("permCode"), "%" + condition.getKeyword() + "%");
                predicates.add(cb.or(appIdMatch, appNameMatch)); // 核心修改点
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        Page<PermissionPO> queryResult = permissionRepository.findAll(spec, pageable);
        PageResult<PermissionPO>  pageResult = new PageResult(queryResult.getNumber(), queryResult.getSize(), queryResult.getTotalElements(), queryResult.getTotalPages());
        pageResult.setList(queryResult.getContent());
        return pageResult;
    }

    @Override
    public List<PermissionPO> listAll(PermissionQueryAllCondition condition) {
        Sort.Direction direction = Sort.Direction.fromString(condition.getDirection());
        Sort sort = Sort.by(direction, condition.getOrderBy());

        Specification<PermissionPO> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (condition.getAppId() != null) {
                predicates.add(cb.equal(root.get("appId"), condition.getAppId() ));
            }

            if (condition.getPermType() != null) {
                predicates.add(cb.equal(root.get("permType"), condition.getPermType() ));
            }

            if (condition.getPermName() != null) {
                predicates.add(cb.like(root.get("permName"), "%" + condition.getPermName() + "%"));
            }

            if (condition.getPermCode() != null) {
                predicates.add(cb.like(root.get("permCode"), "%" + condition.getPermCode() + "%"));
            }

            if (condition.getKeyword() != null) {
                Predicate appIdMatch = cb.like(root.get("permName"), "%" + condition.getKeyword() + "%");
                Predicate appNameMatch = cb.like(root.get("permCode"), "%" + condition.getKeyword() + "%");
                predicates.add(cb.or(appIdMatch, appNameMatch)); // 核心修改点
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return permissionRepository.findAll(spec, sort);
    }

    @Override
    public List<PermissionListVO> po2vo(List<PermissionPO> list) {
        Set<String> appIdSet = new HashSet<>();
        Set<Long> userIdSet = new HashSet<>();
        for(PermissionPO po: list) {
            appIdSet.add(po.getAppId());
            userIdSet.add(po.getCreatedBy());
            userIdSet.add(po.getUpdatedBy());
        }
        List<ApplicationPO> appList = applicationRepository.findAllById(appIdSet);
        List<UserPO> userList = userRepository.findAllById(userIdSet);
        Map<String,String> appId2NameMap;
        Map<Long,String> userId2NameMap;
        if (appList != null) {
            appId2NameMap = appList.stream().collect(Collectors.toMap(ApplicationPO::getAppId,ApplicationPO::getAppName));
        } else {
            appId2NameMap = new HashMap<>(0);
        }

        if (userList != null) {
            userId2NameMap = userList.stream().collect(Collectors.toMap(UserPO::getUserId,UserPO::getUsername));
        } else {
            userId2NameMap = new HashMap<>(0);
        }
        List<PermissionListVO> voList = list.stream().map(po -> {
            PermissionListVO vo = new PermissionListVO();
            BeanUtils.copyProperties(po, vo);
            vo.setAppName(appId2NameMap.get(po.getAppId()));
            vo.setCreatedByName(userId2NameMap.get(po.getCreatedBy()));
            vo.setUpdatedByName(userId2NameMap.get(po.getUpdatedBy()));
            vo.setPermTypeName(PermType.getTypeName(po.getPermType()));
            vo.setPermId(String.valueOf(po.getPermId()));
            vo.setUpdatedBy(String.valueOf(po.getUpdatedBy()));
            vo.setCreatedBy(String.valueOf(po.getCreatedBy()));
            return vo;
        }).toList();
        return voList;
    }
}
